package cn.leftshine.myithome.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import cn.leftshine.myithome.R;
import cn.leftshine.myithome.beans.NewsItem;
import cn.leftshine.myithome.ui.fragment.NewsListFragment.OnListFragmentInteractionListener;
import cn.leftshine.myithome.ui.fragment.dummy.DummyContent.DummyItem;
import cn.leftshine.myithome.utils.DateTool;

import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
 * specified {@link OnListFragmentInteractionListener}.
 * TODO: Replace the implementation with code for your data type.
 */
public class MyNewsRecyclerViewAdapter extends RecyclerView.Adapter<MyNewsRecyclerViewAdapter.ViewHolder> {

    private  List<NewsItem> mValues;
    private final OnListFragmentInteractionListener mListener;
    private Context context;

    public MyNewsRecyclerViewAdapter(List<NewsItem> items, OnListFragmentInteractionListener listener, Context context) {
        this.context = context;
        mValues = items;
        mListener = listener;
    }

    public void update(List<NewsItem> items){
        mValues=items;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_news_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        holder.news_item_title.setText(mValues.get(position).title);
        String dateStr = mValues.get(position).pubDate;//Fri, 14 Sep 2018 02:31:38 GMT
        //Date isoDate = isoStrParseToDate(dateStr);
        Date isoDate = DateTool.isoStrParseToDate(dateStr);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        holder.news_item_time.setText(sdf.format(isoDate));
        holder.news_item_comment.setText(mValues.get(position).comment);
        //先设置图片占位符
        holder.news_item_img.setImageDrawable(context.getResources().getDrawable(R.mipmap.slide_pic_placeholder));
        String description = mValues.get(position).description;
        List<String> imgList = getFirstImgSrc(description);
        if(imgList.size()>0) {
            final String imgSrc = imgList.get(0);
            holder.news_item_img.setTag(imgSrc);
            new AsyncTask() {
                @Override
                protected Object doInBackground(Object[] params) {
                    try {
                        URL picUrl = new URL(imgSrc);
                        Bitmap bitmap = BitmapFactory.decodeStream(picUrl.openStream());
                        return bitmap;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Object o) {
                    super.onPostExecute(o);
                    //加载完毕后判断该imageView等待的图片url是不是加载完毕的这张
                    //如果是则为imageView设置图片,否则说明imageView已经被重用到其他item
                    if (imgSrc.equals(holder.news_item_img.getTag())) {
                        holder.news_item_img.setImageBitmap((Bitmap) o);
                    }
                }
            }.execute();
        }
        else{
            holder.news_item_img.setVisibility(View.GONE);
        }
        /*OkHttpClient client = new OkHttpClient();
        try{
            Request request = new Request.Builder().url(imgSrc).build();
            Response response = client.newCall(request).execute();
            InputStream is = response.body().byteStream();
            Bitmap bm = BitmapFactory.decodeStream(is);
            if(imgSrc.equals(holder.news_item_img.getTag())){
                holder.news_item_img.setImageBitmap(bm);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(holder.mItem);
                }
            }
        });
    }

    private List<String> getFirstImgSrc(String description) {
        String content =description;
        List<String> srcList = new ArrayList<String>(); //用来存储获取到的图片地址
        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");//匹配字符串中的img标签
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        if(hasPic == true)//判断是否含有图片
        {
            while(hasPic) //如果含有图片，那么持续进行查找，直到匹配不到
            {
                String group = matcher.group(2);//获取第二个分组的内容，也就是 (.*?)匹配到的
                Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");//匹配图片的地址
                Matcher matcher2 = srcText.matcher(group);
                if( matcher2.find() )
                {
                    srcList.add( matcher2.group(3) );//把获取到的图片地址添加到列表中
                }
                hasPic = matcher.find();//判断是否还有img标签
            }

        }
        return srcList;

    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView news_item_title,news_item_time,news_item_comment;
        public final ImageView news_item_img;
        public NewsItem mItem;


        public ViewHolder(View view) {
            super(view);
            mView = view;
            news_item_img = view.findViewById(R.id.news_item_img);
            news_item_title=(TextView) view.findViewById(R.id.news_item_title);
            news_item_time = (TextView) view.findViewById(R.id.news_item_time);
            news_item_comment = (TextView) view.findViewById(R.id.news_item_comment);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + news_item_title.getText() + "'";
        }

    }
}
